package org.summerframework.core.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.*;

/**
 * @author 石超
 * @version v1.0.0
 */
@Slf4j
public class JsonJoinListNullSerializer extends JsonSerializer<Object> {
    private Map<String, JsonJoinListSerializer> list = new HashMap<>();
    private static final Map<Class, JsonJoinListNullSerializer> classListMap = new HashMap<>();

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String key = gen.getOutputContext().getCurrentName();
        if (list.containsKey(key)) {
            list.get(key).serialize((List) value, gen, serializers);
        } else {
            gen.writeNull();
        }
    }

    public static JsonJoinListNullSerializer addKey(Class classs, String key, JsonJoinListSerializer jsonJoinListSerializer) {
        JsonJoinListNullSerializer jsonJoinListNullSerializer = classListMap.computeIfAbsent(classs, (k) -> new JsonJoinListNullSerializer());
        jsonJoinListNullSerializer.list.put(key, jsonJoinListSerializer);

        return jsonJoinListNullSerializer;
    }
}
